package com.bjbn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bjbn.bean.ApiCallParams;
import com.bjbn.bean.ApiResult;
import com.bjbn.service.DataphinService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.cloudapi.sdk.constant.SdkConstant;
import com.alibaba.cloudapi.sdk.enums.Scheme;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.dt.dataphin.client.ApiClient;
import com.alibaba.dt.dataphin.client.ApiClientBuilderParams;
import com.alibaba.dt.dataphin.schema.OrderBy;
import com.alibaba.dt.dataphin.schema.QueryParamRequest;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class DataphinServiceImpl implements DataphinService {

    private static final String HOST = "dataphin-dataservice.gdairport.com";
    private static final int CODE = 200;

    @Override
    public ApiResult getDataphinData(ApiCallParams apiCallParams) {
        return callApi(apiCallParams);
    }

    @SuppressWarnings("all")
    private ApiResult callApi(ApiCallParams apiCallParams) {
        /*
        String apiId = "10353";
        String apiType = "LIST";
        String appKey = "200000226";
        String appSecret = "d43bc101cb3b4add8554f821b568c84c";
        String apiReturnFields = "id,flightid,craftsite,starttime,endtime,startrealtime,endrealtime,ordercode";
        String listType = "LIST";
        */
        String apiId = apiCallParams.getApiId();
        String apiType = apiCallParams.getApiType();
        String appKey = apiCallParams.getAppKey();
        String appSecret = apiCallParams.getAppSecret();
        String apiReturnFields = apiCallParams.getApiReturnFields();
        String listType = apiCallParams.getListType();
        Integer currentPage = apiCallParams.getPageStart();
        Integer pageSize = apiCallParams.getPageSize();
        String orderByList = apiCallParams.getOrderByList();


        //创建请求参数 ---------------------------------------
        QueryParamRequest queryParamRequest = new QueryParamRequest();
        //构造请求参数对象
        //---条件参数
        //添加查询条件,其中key为对应的查询字段,value为查询字段对应的值, 例如这里的id为请求字段名,1为id对应的值,可以设置多个查询参数
        HashMap<String, Object> condition = Maps.newHashMap();
        //注意：如果是 IN 类型的参数，使用 list 包装参数值。
        queryParamRequest.setConditions(condition);
        //-- 排序(可选设置)
        // 注意oracle和sqlServer使用分页需要同时使用排序
        // 排序字段,根据返回参数指定升序或者降序, 例如返回结果按id进行升序, 可设置多个字段进行升序或者降序
        // 使用分页则必须指定排序字段，并且要使用排序稳定的字段（例如主键、联合主键）保证每次排序结果相同，避免分页不准确
        ArrayList<OrderBy> orderList = Lists.newArrayList();
        if (orderByList != null && !orderByList.isEmpty()) {
            // Parm1,Parm2 desc,Parm3
            for (String orderBy : Splitter.on(",").split(orderByList)) {
                String[] orderByArr = orderBy.split(" ");
                OrderBy.Order order = OrderBy.Order.ASC;
                if (orderByArr.length > 1) {
                    if (orderByArr[1].equalsIgnoreCase("desc")) {
                        order = OrderBy.Order.DESC;
                    }
                }
                OrderBy orderByColumn = new OrderBy(orderByArr[0], order);
                orderList.add(orderByColumn);
            }
        }
        //OrderBy.Order asc = OrderBy.Order.ASC;
        //OrderBy orderByColumn1 = new OrderBy("your order column", asc);
        //OrderBy orderByColumn2 = new OrderBy("your order column", asc);
        //orderList.add(orderByColumn1);
        //orderList.add(orderByColumn2);
        queryParamRequest.setOrderBys(orderList);
        //指定返回有权限的参数
        List<String> returnFiles = Lists.newArrayList(Splitter.on(",").split(apiReturnFields));
        queryParamRequest.setReturnFields(returnFiles);
        //进行分页(可选).不设置，默认取1~1000条数据
        queryParamRequest.setPageStart(currentPage);
        queryParamRequest.setPageSize(pageSize);
        // 是否缓存查询结果，开启则会缓存同一个API相同条件、想通返回字段的查询结果
        // 适用于数据不变化的查询
        // 缓存时长默认30分钟, 3.5.6 版本后，在开发API时可设置缓存时长
        queryParamRequest.setUseResultCache(true);
        //结束创建请求参数 ---------------------------------------
        ApiClient apiClient = createHttpClient(appKey, appSecret);
        try {
            ApiResponse response = listType.equalsIgnoreCase(apiType)
                    ? apiClient.listSync(apiId, queryParamRequest)
                    : apiClient.getSync(apiId, queryParamRequest);
            String result = new String(response.getBody());
            String code = JSONObject.parseObject(result).get("code").toString();
            return getResultString(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private ApiClient createHttpClient(String appKey, String appSecret) {
        ApiClientBuilderParams params = new ApiClientBuilderParams();
        params.setAppKey(appKey);
        params.setAppSecret(appSecret);
        params.setHost(HOST);
        //默认为http协议, 如果API 支持 HTTPS, 这里也可以设置HTTPS
        params.setScheme(Scheme.HTTP);
        params.setStage("RELEASE");
        params.setEnv("PROD");
        return new ApiClient(params);
    }

    private ApiResult getResultString(ApiResponse response) {
        ApiResult apiResult = new ApiResult();
        apiResult.setResultCode(response.getCode());

        if (response.getHeaders().get("x-ca-request-id") != null) {
            apiResult.setRequestId(response.getHeaders().get("x-ca-request-id").toString());
        }

        if (response.getHeaders().get("x-ca-error-code") != null) {
            apiResult.setErrorCode(response.getHeaders().get("x-ca-error-code").toString());
        }

        if (CODE != response.getCode()) {
            apiResult.setError(response.getHeaders().get("x-ca-error-message").toString());
        }

        apiResult.setResultBody(new String(response.getBody(), SdkConstant.CLOUDAPI_ENCODING));

        return apiResult;
    }


}
